<template>
	<view class="container">
		<view class="btn">
			<uni-tag @click="cancel" text="取消" type="default"></uni-tag>
			<uni-tag @click="confirm" text="确认" type="primary"></uni-tag>
		</view>
		<view>
			<uni-file-picker title="请上传头像" v-model="photo" fileMediatype="image" :limit="1" mode="grid"
				@select="photoUpload" @delete="photoRemove" />
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				avatar: '',
				photo: {}
			}
		},
		methods: {
			// 移除头像
			photoRemove(e) {
				this.photo = {}
			},
			// 头像上传
			async photoUpload(e) {
				this.photo.url = await this.uploadFile(e.tempFilePaths[0])
				this.avatar = this.photo.url
			},
			// 文件上传
			uploadFile(imgUrl) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: 'http://localhost:8080/file/upload',
						header: {
							'Authorization': 'Bearer ' + wx.getStorageSync('token')
						},
						filePath: imgUrl,
						name: 'file',
						success: (resp) => {
							if (resp.statusCode == 200) {
								resolve(JSON.parse(resp.data).data);
							} else {
								reject(new Error('Upload failed'));
							}
						},
					})
				})
			},
			//取消按钮
			cancel() {
				uni.navigateBack()
			},
			//确认按钮
			confirm() {
				let that = this
				let tmp = uni.getStorageSync('userInfo')
				if (this.avatar == '') {
					uni.showToast({
						title: '请先上传头像',
						icon: 'error',
						duration: 2000
					})
				} else {
					uni.request({
						url: 'http://localhost:8080/user/user',
						header: {
							'Authorization': 'Bearer ' + wx.getStorageSync('token')
						},
						method: 'PUT',
						data: {
							id: tmp.id,
							avatar: that.avatar
						},
						success(res) {
							if(res.data.code == 200){
								tmp.avatar = that.avatar
								uni.setStorageSync('userInfo',tmp)
								uni.switchTab({
									url: '/pages/my/my'
								})
							}
						}
					})
				}
			}
		}
	}
</script>

<style>
	page {
		background-color: #fff;
	}

	.container {
		padding: 20rpx 40rpx 0;
	}

	.btn {
		display: flex;
		justify-content: space-between;
		padding-bottom: 20rpx;
	}
</style>